<template>
  <!-- 登录表单 -->
  <div class="login-container">
    <el-card class="login-card">
      <h2 class="login-title">用户登录</h2>
      <el-form ref="loginForm" :model="loginForm" label-width="80px">
        <el-form-item label="用户名" prop="uname">
          <el-input v-model="loginForm.uname" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="密码" prop="upwd">
          <el-input v-model="loginForm.upwd" type="password" placeholder="请输入密码" show-password />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="login" :loading="loading">
            登录
          </el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { ElMessage } from 'element-plus'
import { useUserInfoStore } from "./pinia/userinfo"
import axios from 'axios'

export default {
  data() {
    return {
      loginForm: {
        uname: '',
        upwd: ''
      },
      loading: false,
      userInfoStore: useUserInfoStore()
    }
  },
  methods: {
    login() {
      axios.get(this.$baseUrl.SPRURL+'v2/user/dologin?uname='+this.loginForm.uname+"&upwd="+this.loginForm.upwd)
        .then(response => {
          if (response.data.code === 0) {
            // 将用户信息存储到 Pinia store 中
            this.userInfoStore.setUserInfo(this.loginForm.uname, response.data.data)
            // 将用户名和 token 存储到 localStorage 中
            localStorage.setItem("uname", this.loginForm.uname)
            localStorage.setItem("token", response.data.data)
            this.$router.push('/usermanagement')
          } else {
            ElMessage.error(response.data.msg)
          }
        })
    },
    resetForm() {
      this.$refs.loginForm.resetFields()
    }
  }
}
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-color: #f5f5f5;
}

.login-card {
  width: 450px;
  padding: 30px;
}

.login-title {
  text-align: center;
  margin-bottom: 30px;
  color: #409eff;
}
</style>